//
//  DownLoader.m
//  reLoadImages
//
//  Created by bao_wsfk on 12-7-13.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DownLoader.h"

@implementation DownLoader

#define DOWNLOAD_FEEDBACK_TITLE @"更新中..."
#define DOWNLOAD_FEEDBACK_CANCEL @"取消"

@synthesize connectionRef = connectionRef;

- (void)dealloc{
    [super dealloc];
    //[connectionRef release],connectionRef =nil;
}

- (id)initDownloader:(NSString *)observerName{
    self = [super init];
    if (self) {
        //通知的名字
        notificationName = observerName;
        //初始化请求描述
        requestSummary = [[NSMutableDictionary alloc]init];
        //初始化接受数据
        receivedData = [[NSMutableData alloc]init];
    }
    return self;
}

- (void)makeHTTPRequest:(NSString *)urlAddress{
    
    //首先要保持屏幕处于常亮状态
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    //给求情地址转码 
    
    NSString *requestUrl = [urlAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //创建url
    NSURL *url = [NSURL URLWithString:requestUrl];
    //创建请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:0 timeoutInterval:30.0];
    [request setHTTPMethod:@"GET"];
    
    //创建连接
    self.connectionRef = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    isDone =NO;
    
    [request release];
    
}

-(void)main{
    if (self.connectionRef != nil) {
        do{
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        } while (!isDone);
    }
    
}

//这个方法当请求有响应的时候被调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    
    //首先初始化接收数据的长度
    [receivedData setLength:0];
    
    //然后判断当前响应的状态码
    if ([response respondsToSelector:@selector(statusCode)]) {
        //要想得到请求的状态码 必须先将NSURLResponse 强制转换成NSHTTPURLResponse
        int statusCode = [((NSHTTPURLResponse *)response) statusCode];
        
        //然后判断状态码的值 statusCode >=400说明没有正常请求到地址
        if (statusCode >=400) {
            //取消连接
            [connectionRef cancel];
            //发送错误报告
            NSString *errorMsg = [NSString stringWithFormat:@"请求错误码：%d",statusCode];
            NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:errorMsg forKey:NSLocalizedDescriptionKey];
            NSError *error = [NSError errorWithDomain:@"request status Code" code:statusCode userInfo:errorInfo];
            [self connection:connectionRef didFailWithError:error];
            
        }else {
            //给预加载长度赋值
            expectedData = [response expectedContentLength];
            //为进度条初始化值
            fakeProgress = 0.1;
            //实例化进度条
            [self initProgress];
        }
        
    }
}

//该方法在接收到数据的时候会被调用
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
    //向接收数据变量中填充数据
    [receivedData appendData:data];
    //判断当前预加载长度是否大于-1 如果大于-1
    if (expectedData >-1) {
        
        long long receivedDataLength = (long long)[receivedData length];
        float progress = (float)receivedDataLength / (float)expectedData; 
        
        //设置进度条的进度值
        [progressBar setProgress:progress];
    }else {
        progressBar.progress = progressBar.progress + fakeProgress;
		fakeProgress = fakeProgress/2;
    }
}

//该方法在请求完成后会被调用
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	
    // 请求结束 释放连接
	[connection release];
    isDone =YES;
	//将数据封装到请求描述中
	[requestSummary setObject:receivedData forKey:@"data"];
	[progressAlert dismissWithClickedButtonIndex:progressAlert.cancelButtonIndex animated:YES];
	[self performSelector:@selector(postNotification) withObject:nil afterDelay:0.1];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    
    //释放连接对象
    [connection release];
    isDone =YES;
    
    NSString *errorMsg = [error localizedDescription];
    //获取错误信息 并封装到请求描述中
    [requestSummary setObject:errorMsg forKey:@"error"];
    [progressAlert dismissWithClickedButtonIndex:progressAlert.cancelButtonIndex animated:YES];
    
    //0.1秒之后发送通知
    [self performSelector:@selector(postNotification) withObject:nil afterDelay:0.1];
}

- (void)postNotification{
    //先将屏幕常亮状态取消
    [UIApplication sharedApplication].idleTimerDisabled = NO;
    //获取默认的通知 并发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:requestSummary];
}

- (void)initProgress {
	
	progressWheel = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(124,45,37,37)];
	progressWheel.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
	[progressWheel startAnimating];
	
	progressBar = [[UIProgressView alloc] initWithFrame:CGRectMake(30,95,225,9)];
	progressBar.progressViewStyle = UIProgressViewStyleBar;
	progressBar.progress = 0;
	
	progressAlert = [[UIAlertView alloc] initWithTitle:DOWNLOAD_FEEDBACK_TITLE
											   message:@"\n\n\n"
											  delegate:self
									 cancelButtonTitle:DOWNLOAD_FEEDBACK_CANCEL
									 otherButtonTitles:nil];
	
	[progressAlert addSubview:progressWheel];
	[progressAlert addSubview:progressBar];
	[progressAlert show];
	
	[progressWheel release];
	[progressBar release];
	[progressAlert release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	
	[self cancelConnection];
	[self performSelector:@selector(postNotification) withObject:nil afterDelay:0.1];
}
- (void)cancelConnection {
	
	[connectionRef cancel];
	[connectionRef release];
    isDone =YES;
}


@end
